package com.ruov.plugin.wx.offiaccount.controller;

import cn.hutool.core.util.StrUtil;
import com.ruov.common.annotation.Anonymous;
import com.ruov.common.core.domain.R;
import com.ruov.common.core.redis.RedisCache;
import com.ruov.common.utils.StringUtils;
import com.ruov.common.utils.uuid.UUID;
import com.ruov.plugin.wx.consts.RedisKeyConsts;
import com.ruov.plugin.wx.offiaccount.entity.res.LoginRes;
import com.ruov.plugin.wx.offiaccount.entity.res.WxQRCodeRes;
import com.ruov.plugin.wx.offiaccount.utils.WxQrCodeUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author wjsmc
 * @date 2025/4/24 10:27
 * @description
 **/
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/offiaccount/{appid}")
@Anonymous
public class OffiaccountCommonController {

    private final RedisCache redisCache;
    private final WxMpService wxMpService;
    private final WxQrCodeUtils wxQrCodeUtils;

    /**
     * 获取可验证码
     */
    @PostMapping("/login")
    public R<LoginRes> login(@PathVariable String appid) throws Exception {
        String unique = UUID.fastUUID().toString();
        wxMpService.switchover(appid);
        WxQRCodeRes tempQRCode = wxQrCodeUtils.createTempQRCode(unique, TimeUnit.MINUTES.toSeconds(RedisKeyConsts.Offiaccount.LOGIN_UNIQUE_KEY_EXPIRE));
        if (StrUtil.isEmpty(tempQRCode.getTicket())) {
            return R.fail("获取二维码失败");
        }
        redisCache.setCacheObject(StringUtils.format(RedisKeyConsts.Offiaccount.LOGIN_UNIQUE_KEY, appid, unique), "",
                RedisKeyConsts.Offiaccount.LOGIN_UNIQUE_KEY_EXPIRE, TimeUnit.MINUTES);
        return R.ok(LoginRes.builder()
                .unique(unique)
                .ticket(tempQRCode.getTicket())
                .build());
    }

    /**
     * 扫码校验
     */
    @GetMapping("/checkLogin")
    public R<String> stream(@RequestParam("unique") String unique, @PathVariable String appid) throws Exception {
        if (!redisCache.hasKey(StringUtils.format(RedisKeyConsts.Offiaccount.LOGIN_UNIQUE_KEY, appid, unique))) {
            return R.fail("登录已失效");
        }
        wxMpService.switchover(appid);
        String token = redisCache.getCacheObject(StringUtils.format(RedisKeyConsts.Offiaccount.LOGIN_UNIQUE_KEY, appid, unique));
        if (StrUtil.isEmpty(token)) {
            return R.fail("等待回调中");
        } else {
            try {
                return R.ok(token);
            } finally {
                redisCache.deleteObject(StringUtils.format(RedisKeyConsts.Offiaccount.LOGIN_UNIQUE_KEY, appid, unique));
            }
        }
    }
}
